<%@ page import="com.example.softwareconfigurationcoursedesign.Product" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="com.example.softwareconfigurationcoursedesign.ProductService" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="jakarta.servlet.http.Cookie" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page import="com.google.gson.reflect.TypeToken" %>
<%@ page import="com.google.gson.Gson" %>

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>购物车</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .product_img {
            max-width: 100px;
            max-height: 100px;
        }
    </style>
</head>
<body>
<h1>购物车</h1>
<table>
    <tr>
        <th>图片</th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th> <!-- 添加操作列 -->
    </tr>
    <%-- Java代码部分，获取购物车中的商品信息并展示 --%>
    <%
        Connection connection;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String jdbcUrl = "jdbc:mysql://localhost:3306/course_design";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(jdbcUrl, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    %>
    <%
        List<String> cartItems = new ArrayList<>();
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals("cart")) {
                    String cartJSON = URLDecoder.decode(cookie.getValue(), "UTF-8");
                    cartItems = new Gson().fromJson(cartJSON, new TypeToken<List<String>>(){}.getType());
                    break;
                }
            }
        }

        ProductService productService = new ProductService();
        double totalPrice = 0.0;
    %>
    <% for (String itemName : cartItems) { %>
    <% List<Product> productList = productService.getProductListCarFromDatabase(itemName); %>
    <% for (Product product : productList) { %>
    <tr>
        <td>
            <img src="<%= product.getPurl() %>" alt="<%= product.getPname() %>" class="product_img">
        </td>
        <td><%= product.getPname() %></td>
        <td>￥<%= product.getPprice() %></td>
        <td>1</td>
        <td>
            <button onclick="removeItem('<%= product.getPname() %>')">移除</button> <!-- 添加移除按钮 -->
        </td>
    </tr>
    <% totalPrice += product.getPprice(); %>
    <% } %>
    <% } %>

    <tr>
        <td colspan="3"></td>
        <td>商品总价：￥<span id="totalPrice"><%= totalPrice %></span></td>
    </tr>
    <tr>
        <td colspan="4">
            <button onclick="clearCart()">清空购物车</button>
            <button onclick="refreshPage()">刷新页面</button>
        </td>
    </tr>

</table>
</body>
<script>
    // 清空购物车
    function clearCart() {
        document.cookie = "cart=;expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        location.reload();
    }

    // 刷新页面
    function refreshPage() {
        location.reload();
    }
    function removeItem(name) {
        let cart = [];
        if (document.cookie.includes('cart=')) {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.startsWith('cart=')) {
                    const cartJSON = decodeURIComponent(cookie.substring(5));
                    cart = JSON.parse(cartJSON);
                    break;
                }
            }
        }
        // 查找并移除商品名称
        const index = cart.indexOf(name);
        if (index !== -1) {
            cart.splice(index, 1);
            const cartJSON = JSON.stringify(cart);
            document.cookie = 'cart=' + encodeURIComponent(cartJSON) + '; expires=Thu, 01 Jan 2024 00:00:00 UTC; path=/;';
            window.alert('商品 ' + name + ' 已从购物车中移除');
        }
    }
</script>

</html>
